/**
 * 雪碧图生成任务实例,该方法将会遍历sprite目录下的子目录，子目录名称为前缀。子目录必须由字母组成
 * 雪碧图存放位置：src/assets/sprite-assets/ ，按文件夹区分
 */

let walk = require('walk')

module.exports = function (gulp, plugins, config) {
    /**
     * 雪碧图生成配置
     * @param prefix css前缀 ，也是图标所在目录，必填
     * @returns {*}
     * 生成less和png，分别存放于./src/less/ ./src/images/
     */
    function spritesmithConfig(prefix, options) {
        var sprite_config = {
            imgName: prefix + '.png',
            cssName: 'sprite-' + prefix + '.less',
            cssFormat: 'less',
            cssSpritesheetName:prefix,
            cssOpts: {
                prefix: prefix,
                distpath: '../assets/sprites/'  // css中生成图标的路径
            },
            cssTemplate: './gulp/sprite/less.px.template.handlebars', //如果是移动端可以选用rem模板
            cssHandlebarsHelpers:{
                px2percent:function (sprite) {
                    var position_x = sprite.offset_x/(sprite.width - sprite.total_width)*100;
                    var position_y = sprite.offset_y/(sprite.height - sprite.total_height)*100;
                    return  (position_x===0?"0 ":position_x.toFixed(2) + "% ") + (position_y===0?"0":position_y.toFixed(2) + "%").replace(/\.00/g,"");
                }
            }
        };
        sprite_config = Object.assign({},sprite_config,options);
        return gulp.src( config.src + 'assets/sprite-assets/' + prefix + '/*' )
            .pipe( plugins.spritesmith( sprite_config ) )
            .pipe( plugins.if('*.png', gulp.dest(config.src + 'assets/sprites/'), gulp.dest( config.src + 'less/' )) );
    }


    function run(done) {
        var walker  = walk.walk( config.src + "assets/sprite-assets", { followLinks: false });
        walker.on("directories", function (root, dirStatsArray, next) {
            for( var i=0, len = dirStatsArray.length; i<len; i++ ){
                spritesmithConfig( dirStatsArray[i].name, { padding:5 })
            }
            next();
        });
        done();
    }

    return gulp.series(run)


}

